<template>
  <div class="user-role-manage">
    <h1 class="page-title">用户角色分配</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户名/手机号"
            clearable
            style="width: 240px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" width="250">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.avatar" :size="40">{{ row.nickname?.charAt(0) }}</el-avatar>
              <div class="user-detail">
                <div class="nickname">{{ row.nickname }}</div>
                <div class="contact">{{ row.phone || row.email || '-' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="当前角色" width="300">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              size="small"
              style="margin-right: 5px"
            >
              {{ role.name }}
            </el-tag>
            <span v-if="!row.roles || row.roles.length === 0" style="color: #909399">
              未分配角色
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleAssignRole(row)"
            >
              <el-icon><Edit /></el-icon>
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 分配角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="分配角色"
      width="600px"
      @close="handleDialogClose"
    >
      <div v-if="currentUser" class="dialog-content">
        <div class="user-info-section">
          <el-avatar :src="currentUser.avatar" :size="60">
            {{ currentUser.nickname?.charAt(0) }}
          </el-avatar>
          <div class="user-info-text">
            <div class="nickname">{{ currentUser.nickname }}</div>
            <div class="user-id">ID: {{ currentUser.id }}</div>
          </div>
        </div>

        <el-divider />

        <el-form label-width="100px">
          <el-form-item label="选择角色">
            <el-checkbox-group v-model="selectedRoles">
              <div v-for="role in allRoles" :key="role.id" class="role-item">
                <el-checkbox :label="role.id">
                  <span class="role-name">{{ role.name }}</span>
                  <el-tag size="small" type="info" style="margin-left: 10px">
                    {{ role.code }}
                  </el-tag>
                </el-checkbox>
                <div class="role-description">{{ role.description || '暂无描述' }}</div>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/user'
import { roleApi, userRoleApi } from '@/api/role'
import dayjs from 'dayjs'

// 数据
const loading = ref(false)
const userList = ref([])
const allRoles = ref([])
const currentUser = ref(null)
const selectedRoles = ref([])
const dialogVisible = ref(false)
const submitting = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 加载角色列表
const loadRoles = async () => {
  try {
    const res = await roleApi.getAllRoles()
    allRoles.value = res || []
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  }
}

// 加载用户列表
const loadData = async () => {
  loading.value = true
  try {
    const res = await userApi.getUserList({
      page: pagination.page,
      page_size: pagination.pageSize,
      keyword: searchForm.keyword
    })
    userList.value = res.records || []
    pagination.total = res.total || 0

    // 为每个用户加载角色信息
    for (const user of userList.value) {
      try {
        const roles = await userRoleApi.getUserRoles(user.id)
        user.roles = roles || []
      } catch (error) {
        console.error(`加载用户${user.id}角色失败:`, error)
        user.roles = []
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  handleSearch()
}

// 分配角色
const handleAssignRole = async (row) => {
  currentUser.value = row
  
  // 获取用户当前的角色ID列表
  selectedRoles.value = row.roles ? row.roles.map(r => r.id) : []
  
  dialogVisible.value = true
}

// 提交角色分配
const handleSubmit = async () => {
  if (!currentUser.value) return
  
  submitting.value = true
  try {
    // 调用API分配角色
    await userRoleApi.assignRoles(currentUser.value.id, selectedRoles.value)
    
    ElMessage.success('角色分配成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('角色分配失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 分页
const handlePageChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 对话框关闭
const handleDialogClose = () => {
  currentUser.value = null
  selectedRoles.value = []
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 生命周期
onMounted(() => {
  loadRoles()
  loadData()
})
</script>

<style scoped lang="scss">
.user-role-manage {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .user-detail {
      .nickname {
        font-weight: 500;
        color: #303133;
      }

      .contact {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-content {
  .user-info-section {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;

    .user-info-text {
      .nickname {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }

      .user-id {
        font-size: 14px;
        color: #909399;
        margin-top: 5px;
      }
    }
  }

  .role-item {
    margin-bottom: 15px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    .role-name {
      font-weight: 500;
    }

    .role-description {
      margin-left: 24px;
      margin-top: 5px;
      font-size: 12px;
      color: #909399;
    }
  }
}
</style>

